package com.yyfax.ph.personal.authority.gesture;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.Loader;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import com.yyfax.common.CLog;
import com.yyfax.common.lockpattern.LockPatternView;
import com.yyfax.common.lockpattern.LockPatternViewShadow;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.ph.R;
import com.yyfax.ph.base.BaseActivity;
import com.yyfax.ph.base.YJPH;
import com.yyfax.ph.common.utils.preferenceutils.PreferenceConstants;
import com.yyfax.ph.main.MainActivity;
import com.yyfax.ph.personal.authority.login.LoginActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by laixj on 2017/3/6.
 * Copyright ©2016 www.yylending.com. All Rights Reserved.
 */
public class ValidateGesturesActivity extends BaseActivity implements View.OnClickListener {
	private final static String TAG = "ValidateGesturesActivity";

	private final static long DELAY_TIME = 600L;
	private static Intent mIntent;

	@BindView(R.id.gesture_validate_pattern)
	LockPatternViewShadow mLockPattern;
	@BindView(R.id.gesture_validate_message)
	TextView mMessage;
	@BindView(R.id.gesture_validate_forget)
	TextView mForgetTv;

	private List<LockPatternView.Cell> mChosenPattern = new ArrayList<>();
	private Status mStatus;

	public static void start(Activity aty) {
		Intent i = new Intent(aty, ValidateGesturesActivity.class);
		aty.startActivity(i);
	}

	public static void start(Context aty, Intent intent) {
		Intent i = new Intent(aty, ValidateGesturesActivity.class);
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		mIntent = intent;
		aty.startActivity(i);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		YJPH.getInstance().getPreferenceManager().savePreference(PreferenceConstants.SP_KEY_VALIDATE_GESTURE, true);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (!GesturesPresenter.readStatus() || !YJPH.getInstance().hadLockPattern()) {
			finish();
		}
	}

	@Override
	public void pretreatmentAfterSetBaseView() {

	}

	@Override
	public int getTopBarBackgroundColor() {
		return ContextCompat.getColor(this, R.color.color_3493e8);
	}

	@Override
	public int getContentViewRes() {
		return R.layout.activity_gestures_validate;
	}

	@Override
	public void initContentView() {
		setTopBarVisible(false);
		mLockPattern.setOnPatternListener(mListener);
		updateStatus(Status.VALIDATE, null);
	}

	private LockPatternView.OnPatternListener mListener = new LockPatternView.OnPatternListener() {
		@Override
		public void onPatternStart() {
			CLog.i(TAG, "onPatternStart mStatus=" + mStatus);
			mLockPattern.removePostClearPatternRunnable();
			mLockPattern.setPattern(LockPatternView.DisplayMode.DEFAULT);
		}

		@Override
		public void onPatternComplete(List<LockPatternView.Cell> pattern) {
			CLog.i(TAG, "onPatternComplete mStatus=" + mStatus);
			switch (mStatus) {
				case VALIDATE:
				case VALIDATE_ERROR:
					if (YJPH.getInstance().checkChosenPattern(pattern)) {
						GesturesPresenter.resetGestureCount();
						updateStatus(Status.CONFIRM_CORRECT, pattern);
					} else {
						updateStatus(Status.VALIDATE_ERROR, null);
					}
					break;
				case DEFAULT:
					mChosenPattern.clear();
					mChosenPattern.addAll(pattern);
					updateStatus(Status.CORRECT, pattern);
					break;
				case CORRECT:
					if (mChosenPattern.equals(pattern)) {
						GesturesPresenter.resetGestureCount();
						updateStatus(Status.CONFIRM_CORRECT, pattern);
					} else {
						updateStatus(Status.CONFIRM_ERROR, pattern);
					}
					break;
			}
		}
	};

	/**
	 * 更新状态
	 */
	protected void updateStatus(Status status, List<LockPatternView.Cell> pattern) {
		mStatus = status;
		mMessage.setTextColor(getResources().getColor(status.colorId));
		if (mStatus.strId == Status.VALIDATE_ERROR.strId) {
			mMessage.setText(String.format(getString(status.strId), GesturesPresenter.getGestureRemainCount()));
		} else {
			mMessage.setText(status.strId);
		}
		switch (status) {
			case VALIDATE:
			case VALIDATE_ERROR:
				if (status == Status.VALIDATE_ERROR) {
					CLog.i(TAG, "剩余解锁次数-->" + GesturesPresenter.getGestureRemainCount());
					if (GesturesPresenter.getGestureRemainCount() <= 0) {
						updateStatus(Status.VALIDATE_RETRY_MAX, null);
						YJPH.getInstance().clearGesture(false);
						YJPH.getInstance().onLogoutSuccess();
						MainActivity.start(this, true);
						finish();
						break;
					}
					int count = GesturesPresenter.getGestureCount();
					CLog.i(TAG, "count GesturesPresenter.getGestureCount()-->" + GesturesPresenter.getGestureCount());
					GesturesPresenter.setGestureCount(count + 1);
				}
				mLockPattern.setPattern(LockPatternView.DisplayMode.NORMAL);
				mLockPattern.postClearPatternRunnable(DELAY_TIME);
				break;
			case VALIDATE_RETRY_MAX:
				mLockPattern.setEnabled(false);
				break;
			case DEFAULT:
				mLockPattern.setPattern(LockPatternView.DisplayMode.DEFAULT);
				break;
			case CORRECT:
				mLockPattern.setPattern(LockPatternView.DisplayMode.DEFAULT);
				break;
			case LESS_ERROR:
				mLockPattern.setPattern(LockPatternView.DisplayMode.DEFAULT);
				break;
			case CONFIRM_ERROR:
				mLockPattern.setPattern(LockPatternView.DisplayMode.ERROR);
				mLockPattern.postClearPatternRunnable(DELAY_TIME);
				break;
			case CONFIRM_CORRECT:
				mLockPattern.setPattern(LockPatternView.DisplayMode.DEFAULT);
				validatePatternSuccess();
				break;
		}
	}

	@OnClick(R.id.gesture_validate_forget)
	public void onClick(View view) {
		super.onClick(view);
		switch (view.getId()) {
			case R.id.gesture_validate_forget:
				LoginActivity.start(this, true);
				break;
		}
	}

	protected enum Status {
		/**
		 * 验证原始手势密码
		 */
		VALIDATE(R.string.unlock_gesture, R.color.color_white),
		VALIDATE_ERROR(R.string.create_gesture_validate_error, R.color.color_white),
		VALIDATE_RETRY_MAX(R.string.create_gesture_retry_max, R.color.color_white),
		/**
		 * 默认的状态，刚开始的时候（初始化状态）
		 */
		DEFAULT(R.string.create_gesture_default, R.color.color_white),
		/**
		 * 第一次记录成功
		 */
		CORRECT(R.string.create_gesture_correct, R.color.color_white),
		/**
		 * 连接的点数小于4（二次确认的时候就不再提示连接的点数小于4，而是提示确认错误）
		 */
		LESS_ERROR(R.string.create_gesture_less_error, R.color.color_white),
		/**
		 * 二次确认错误
		 */
		CONFIRM_ERROR(R.string.create_gesture_confirm_error, R.color.color_white),
		/**
		 * 二次确认正确
		 */
		CONFIRM_CORRECT(R.string.create_gesture_validate_correct, R.color.color_white),
		CREATE_GESTURE(R.string.create_gesture_new, R.color.color_white),
		CONFIRM_GESTURE(R.string.create_gesture_correct, R.color.color_white);

		private int strId;
		private int colorId;

		Status(int strId, int colorId) {
			this.strId = strId;
			this.colorId = colorId;
		}
	}

	private void validatePatternSuccess() {
		YJPH.getInstance().getPreferenceManager().savePreference(PreferenceConstants.SP_KEY_VALIDATE_GESTURE, false);
		CLog.i(TAG, "手势验证成功");
		if(mIntent != null) {
			startActivity(mIntent);
		}
		finish();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			CLog.i(TAG, "手势验证back");
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {

	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		return null;
	}
}
